package com.shengqi.xinnongren.work.ui.goods.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.utils.HtmlUtil;
import com.shengqi.xinnongren.common.utils.ScreenUtils;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.dialog.AddToCartDialog;
import com.shengqi.xinnongren.work.dialog.SpecificationDialog;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.goods.adapter.BannerPagerAdapter;
import com.shengqi.xinnongren.work.ui.goods.adapter.CommentsAdapter;
import com.shengqi.xinnongren.work.ui.goods.model.CommentBean;
import com.shengqi.xinnongren.work.ui.goods.model.GoodsBanner;
import com.shengqi.xinnongren.work.ui.goods.model.GoodsDetailBean;
import com.shengqi.xinnongren.work.ui.goods.presenter.GoodsDetailsPresenter;
import com.shengqi.xinnongren.work.ui.goods.view.GoodsDetailsView;
import com.shengqi.xinnongren.work.ui.user.activities.ServiceActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;

/**
 * 商品详情
 */
public class GoodsDetailsActivity extends BaseMvpActivity<GoodsDetailsView, GoodsDetailsPresenter> implements GoodsDetailsView {

    private static final String EXTRA_GOODS_ID = "goods_id";
    @BindView(R.id.rv_goods_content)
    RecyclerView mRvGoodsContent;
    @BindView(R.id.tb_switch_content)
    TabLayout mTbSwitchContent;
    @BindView(R.id.sr_refresh)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.iv_collection)
    ImageView iv_collection;
    @BindView(R.id.tv_carNum)
    TextView tv_carNum;

    GoodsDetailBean mGoodsDetailBean;
    String mGoodsId;

    private boolean mIsFromScrollState = false;
    private GoodsDetailsAdapter mGoodsDetailsAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private String[] mTabTitles = {"商品", "详情", "评价"};

    public static void start(Context context, String goodsId) {
        Intent intent = new Intent(context, GoodsDetailsActivity.class);
        intent.putExtra(EXTRA_GOODS_ID, goodsId);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_goods_details;
    }

    @Override
    protected void initView() {
        requestTranslucentStatusBar(Color.TRANSPARENT, false);
        initTabs();
        initRecyclerView();
        mSwipeRefreshLayout.setOnRefreshListener(this::getData);
    }

    private void initTabs() {
        for (String title : mTabTitles) {
            mTbSwitchContent.addTab(mTbSwitchContent.newTab().setText(title));
        }
        mTbSwitchContent.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (mIsFromScrollState) {
                    mIsFromScrollState = false;
                    return;
                }
                mRvGoodsContent.scrollToPosition(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initRecyclerView() {
        mGoodsDetailsAdapter = new GoodsDetailsAdapter();
        mRvGoodsContent.setAdapter(mGoodsDetailsAdapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mRvGoodsContent.setLayoutManager(mLinearLayoutManager);
        mRvGoodsContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                mIsFromScrollState = true;
                TabLayout.Tab tab = mTbSwitchContent.getTabAt(mLinearLayoutManager.findFirstVisibleItemPosition());
                if (tab != null) {
                    tab.select();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        mGoodsId = getIntent().getStringExtra(EXTRA_GOODS_ID);
        mSwipeRefreshLayout.setRefreshing(true);
        mPresenter.getGoodsDetails(mGoodsId);
    }

    @Override
    public void onGetGoodsDetailsSucceed(GoodsDetailBean goodsDetailBean) {
        resetRefreshLayout();
        mGoodsDetailBean = goodsDetailBean;
        if (mGoodsDetailBean.getShoppingCartNum() <= 0) {
            tv_carNum.setVisibility(View.GONE);
        } else {
            tv_carNum.setVisibility(View.VISIBLE);
            tv_carNum.setText(String.valueOf(mGoodsDetailBean.getShoppingCartNum()));
        }
        iv_collection.setImageResource(mGoodsDetailBean.getIsCollect() == 1 ? R.mipmap.ic_collected : R.mipmap.ic_collect);
        mGoodsDetailsAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCollectionRes(int state) {
        iv_collection.setImageResource(state == 1 ? R.mipmap.ic_collected : R.mipmap.ic_collect);
    }

    class GoodsDetailsAdapter extends RecyclerView.Adapter {

        static final int TYPE_GOODS_PREVIEW = 0;
        static final int TYPE_GOODS_DETAILS = 1;
        static final int TYPE_GOODS_COMMENTS = 2;

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            switch (getItemViewType(viewType)) {
                case TYPE_GOODS_PREVIEW:
                    GoodsPreviewHolder previewHolder = new GoodsPreviewHolder(getLayoutInflater().inflate(R.layout.layout_goods_details_preview, parent, false));
                    previewHolder.flBannerContainer.getLayoutParams().height = ScreenUtils.getScreenWidth(GoodsDetailsActivity.this);
                    previewHolder.tvGoodsParameters.setOnClickListener(v -> {
                        if (mGoodsDetailBean == null)
                            return;
                        if (mGoodsDetailBean.getParameter() == null || mGoodsDetailBean.getParameter().isEmpty()) {
                            ToastHelper.getInstance(GoodsDetailsActivity.this).showWarn("暂无参数");
                            return;
                        }
                        new SpecificationDialog.Builder(GoodsDetailsActivity.this)
                                .setDataList(mGoodsDetailBean.getParameter())
                                .build()
                                .show();
                    });
                    return previewHolder;
                case TYPE_GOODS_DETAILS:
                    return new GoodsDetailsHolder(getLayoutInflater().inflate(R.layout.layout_goods_details_description, parent, false));
                case TYPE_GOODS_COMMENTS:
                    GoodsCommentsHolder goodsCommentsHolder = new GoodsCommentsHolder(getLayoutInflater().inflate(R.layout.layout_goods_details_comments, parent, false));
                    goodsCommentsHolder.tvBrowseMore.setOnClickListener(v -> GoodsCommentActivity.start(GoodsDetailsActivity.this, mGoodsId));
                    return goodsCommentsHolder;
            }
            return new GoodsPreviewHolder(getLayoutInflater().inflate(R.layout.layout_goods_details_preview, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (mGoodsDetailBean == null)
                return;
            switch (getItemViewType(position)) {
                case TYPE_GOODS_PREVIEW:
                    GoodsPreviewHolder previewHolder = ((GoodsPreviewHolder) holder);
                    String[] pics = mGoodsDetailBean.getDeputyPic().split(",");
                    List<GoodsBanner> goodsBannerList = convertBanner(pics);
                    previewHolder.setBanner(goodsBannerList);
                    previewHolder.tvTitle.setText(mGoodsDetailBean.getComName());
                    previewHolder.tvDesc.setText(mGoodsDetailBean.getPhrase());
                    previewHolder.tvPrice.setText(String.format("￥%s", mGoodsDetailBean.getPrice()));
                    previewHolder.tvUnit.setText(mGoodsDetailBean.getUnitName());
                    previewHolder.tvOriginPlace.setText(mGoodsDetailBean.getOriginPlace());
                    break;
                case TYPE_GOODS_DETAILS:
                    GoodsDetailsHolder detailsHolder = ((GoodsDetailsHolder) holder);
                    detailsHolder.webView.loadDataWithBaseURL(
                            null,
                            HtmlUtil.getHtmlData(mGoodsDetailBean.getContent() == null ? "" : mGoodsDetailBean.getContent()),
                            "text/html;charset=utf-8",
                            null, null);
                    break;
                case TYPE_GOODS_COMMENTS:
                    GoodsDetailBean.ApiValuationBean apiValuation = mGoodsDetailBean.getApiValuation();
                    GoodsCommentsHolder goodsCommentsHolder = ((GoodsCommentsHolder) holder);
                    goodsCommentsHolder.setCommentList(mGoodsDetailBean.getCommentList());
                    goodsCommentsHolder.tvCommentCount.setText(String.format("(%s人评论)", apiValuation.getAllNum()));
                    goodsCommentsHolder.tvScore.setText(String.format("%s分", apiValuation.getScore()));
                    goodsCommentsHolder.rbScore.setRating(apiValuation.getScore());
                    break;
            }
        }

        @Override
        public int getItemCount() {
            return 3;
        }

        @Override
        public int getItemViewType(int position) {
            switch (position) {
                case 0:
                    return TYPE_GOODS_PREVIEW;
                case 1:
                    return TYPE_GOODS_DETAILS;
                case 2:
                    return TYPE_GOODS_COMMENTS;
            }
            return TYPE_GOODS_PREVIEW;
        }

        class GoodsPreviewHolder extends RecyclerView.ViewHolder implements ViewPager.OnPageChangeListener {
            @BindView(R.id.vp_goods_preview)
            ViewPager vpPreview;
            @BindView(R.id.ll_indicator_container)
            LinearLayout llIndicatorContainer;
            @BindView(R.id.fl_banner_container)
            FrameLayout flBannerContainer;
            @BindView(R.id.tv_title)
            TextView tvTitle;
            @BindView(R.id.tv_desc)
            TextView tvDesc;
            @BindView(R.id.tv_origin_place)
            TextView tvOriginPlace;
            @BindView(R.id.tv_price)
            TextView tvPrice;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_goods_parameters)
            TextView tvGoodsParameters;

            private int defaultIndicatorBg = R.drawable.bg_goods_pic_indicator_gray;
            private int selectedIndicatorBg = R.drawable.bg_goods_pic_indicator_green;

            List<GoodsBanner> mBannerList = new ArrayList<>();
            private BannerPagerAdapter mAdapter;
            private float mDensity;

            GoodsPreviewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                initBanner();
            }

            private void initBanner() {
                mAdapter = new BannerPagerAdapter(mBannerList, GoodsDetailsActivity.this);
                vpPreview.setAdapter(mAdapter);
                vpPreview.setOffscreenPageLimit(mBannerList.size());
                vpPreview.setOnPageChangeListener(this);
            }

            void setBanner(List<GoodsBanner> bannerList) {
                mBannerList.clear();
                mBannerList.addAll(bannerList);
                initIndicator(bannerList);
                mAdapter.notifyDataSetChanged();
                if (bannerList.size() > 0)
                    if (bannerList.size() > 1)
                        vpPreview.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % mBannerList.size());
                    else
                        vpPreview.setCurrentItem(Integer.MAX_VALUE / 2);
            }

            /**
             * 初始化指示器
             *
             * @param bannerList
             */
            private void initIndicator(List<GoodsBanner> bannerList) {
                llIndicatorContainer.removeAllViews();
                for (int i = 0; i < bannerList.size(); i++) {
                    mDensity = getResources().getDisplayMetrics().density;
                    View child = new View(GoodsDetailsActivity.this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (mDensity * 8), (int) (mDensity * 8));
                    if (i != 0)
                        params.leftMargin = (int) (mDensity * 10);
                    llIndicatorContainer.addView(child, params);
                }
                selectIndicator(0);
            }


            /**
             * 选择指示器
             *
             * @param position
             */
            private void selectIndicator(int position) {
                for (int i = 0; i < llIndicatorContainer.getChildCount(); i++) {
                    if (i == position)
                        llIndicatorContainer.getChildAt(position).setBackgroundResource(selectedIndicatorBg);
                    else
                        llIndicatorContainer.getChildAt(i).setBackgroundResource(defaultIndicatorBg);
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                position = mBannerList.size() == 0 ? 0 : position % mBannerList.size();
                selectIndicator(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //当ViewPager滑动停止时，释放播放器资源
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    JZVideoPlayer.releaseAllVideos();
                }
            }
        }

        class GoodsDetailsHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.wv_web)
            WebView webView;

            GoodsDetailsHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }


        class GoodsCommentsHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.rv_goods_comments)
            RecyclerView rvComments;
            @BindView(R.id.tv_browse_more)
            TextView tvBrowseMore;
            @BindView(R.id.tv_comment_count)
            TextView tvCommentCount;
            @BindView(R.id.tv_score)
            TextView tvScore;
            @BindView(R.id.rb_score)
            RatingBar rbScore;

            List<CommentBean> mCommentBeanList = new ArrayList<>();
            private CommentsAdapter mAdapter;

            GoodsCommentsHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                initComment();
            }

            private void initComment() {
                mAdapter = new CommentsAdapter(GoodsDetailsActivity.this, mCommentBeanList);
                rvComments.setAdapter(mAdapter);
                rvComments.setLayoutManager(new LinearLayoutManager(GoodsDetailsActivity.this));
            }

            void setCommentList(List<CommentBean> commentList) {
                mCommentBeanList.clear();
                mCommentBeanList.addAll(commentList);
                mAdapter.notifyDataSetChanged();
            }
        }


    }

    private List<GoodsBanner> convertBanner(String[] pics) {
        List<GoodsBanner> banners = new ArrayList<>();
        for (String pic : pics) {
            String p = pic.toLowerCase();
            if (p.contains("mp4")) {
                banners.add(0, new GoodsBanner(pic, GoodsBanner.Media.VIDEO));
            } else {
                banners.add(new GoodsBanner(pic, GoodsBanner.Media.PICTURE));
            }
        }
//        banners.add(new GoodsBanner("https://v.tvcbook.com/v3/03a79912-808a-11e8-b2b5-00163e10aee6/e993852c702140009e159effcb478837-mp4-hd.mp4", GoodsBanner.Media.VIDEO));
        return banners;
    }

    /**
     * 客服
     */
    @OnClick(R.id.ll_service)
    void ll_service() {
        startActivity(new Intent(this, ServiceActivity.class));
    }

    /**
     * 收藏
     */
    @OnClick(R.id.ll_collect)
    void ll_collect() {
        if (Global.checkLogin(this))
            mPresenter.collectionGoods(mGoodsId);
    }

    /**
     * 购物车
     */
    @OnClick(R.id.ll_shop_cart)
    void ll_shop_cart() {
        if (Global.checkLogin(this)) {
            startActivity(new Intent(this, ShoppingCartActivity.class));
        }
    }


    /**
     * 加入购物车
     */
    @OnClick(R.id.tv_add_to_cart)
    void tv_add_to_cart() {
        if (Global.checkLogin(this)) {
            new AddToCartDialog.Builder(this)
                    .setGoodsId(mGoodsId)
                    .setListener(dialog -> getData())
                    .build()
                    .show();
        }
    }

    @Override
    protected GoodsDetailsPresenter createPresenter() {
        return new GoodsDetailsPresenter();
    }

    @Override
    public void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
        resetRefreshLayout();
        ToastHelper.getInstance(this).showWarn("获取详情失败");
    }

    private void resetRefreshLayout() {
        mSwipeRefreshLayout.setRefreshing(false);
    }
}
